package com.sw.haruka.module.share.server;

import com.sw.haruka.helper.utils.FileUtils;
import com.sw.haruka.helper.utils.LogMgr;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Swsbty on 2021/05/28
 */
public class Server {

    private List<Task> tasks;
    private ServerManager manager;
    private ScheduledExecutorService receiver;
    private ServerSocket core;
    private int port = 9527;


    public Server(ServerManager manager) {
        this.manager = manager;
        this.tasks = new ArrayList<>();
        this.receiver = new ScheduledThreadPoolExecutor(1);
        try {
            this.core = new ServerSocket(port);
        } catch (IOException e) {
            LogMgr.INSTANCE.d("init server error!");
            e.printStackTrace();
        }
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                receiving();
            }
        };
        this.receiver.schedule(runnable, 500, TimeUnit.MILLISECONDS);
    }

    /**
     * receive task request info
     */
    private void receiving() {
        try {
            Socket request = core.accept();
            String requestContent = FileUtils.readString(request.getInputStream());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<Task> getCurrentTasks() {
        return new ArrayList<>(tasks);
    }

    public void addTask(Task task) {
        tasks.add(task);
    }

    private void notifyNewTask(Task task) {
        manager.notifyNewTask(task);
    }
}
